package com.ovo.dailypayaccount.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ovo.dailypayaccount.entity.UserInfo;
import com.ovo.dailypayaccount.service.BaseUserService;
import com.ovo.dailypayaccount.utils.HttpUtils;
import com.ovo.dailypayaccount.utils.PasswordEncryption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Controller
public class LoginController {
	Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private BaseUserService userService;

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ModelAndView result = new ModelAndView("index");
		request.setAttribute("returnMessage", "success");
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		log.info(">>>>>>>用户"+userName+"开始登录。");
		UserInfo user = null;
		if (null != userName && null != password) {
			user = userService.getUserByName(userName);
			if (null != user) {
				boolean pwdboolean = PasswordEncryption.authenticate(password, user.getPassword(), user.getXcode());
				if (!pwdboolean) {
					result.setViewName("login");
					request.setAttribute("returnMessage", "用户密码错误，请检查后重新输入！！！");
					return result;
				}
			} else {
				result.setViewName("login");
				request.setAttribute("returnMessage", "用户不存在，请检查后重新输入！！！");
				return result;
			}
		} else {
			result.setViewName("login");
			return result;
		}
		Cookie cookie = new Cookie("userId", user.getId().toString());
		response.addCookie(cookie);
		cookie.setMaxAge(60 * 60);// 有效期1小时
		result.addObject("userName", user.getName());
		log.info(">>>>>>>用户"+userName+"登录成功。");
		return result;
	}

	@RequestMapping("/toSignup")
	public ModelAndView toSignup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ModelAndView result = new ModelAndView("login");
		request.setAttribute("returnMessage", "success");
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		log.info(">>>>>>>用户"+userName+"开始注册。");
		UserInfo user = new UserInfo();
		user.setName(userName);
		String salt = PasswordEncryption.generateSalt();
		String ciphertext = PasswordEncryption.getEncryptedPassword(password, salt);
		user.setPassword(ciphertext);
		user.setXcode(salt);
		user.setRoleId(0);
		user.setStatus(1);
		user.setCreateTime(new Date());
		boolean backFlag = userService.addUser(user);
		if (!backFlag) {// 注册失败
			request.setAttribute("returnMessage", "注册失败，请检查后重新输入！！！");
		} else {
			request.setAttribute("returnMessage", "注册成功，请登录！");
			log.info(">>>>>>>用户"+userName+"注册成功。");
		}
		return result;
	}

	/**
	 * 重新加载主页
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/reloadIndex")
	public ModelAndView reloadIndex(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView result = new ModelAndView("index");
		Cookie[] cookies = request.getCookies();
		UserInfo user = null;
		String userId = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("userId")) {
					userId = cookie.getValue();
				}
			}
			if (userId != null) {
				user = userService.getUserById(Integer.valueOf(userId));
				if (user != null) {
					result.addObject("userName", user.getName());
					return result;
				}
			} else {
				result.setViewName("login");
			}
		}
		return result;
	}

	/**
	 * 重新加载主页
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView result = new ModelAndView("login");
		request.setAttribute("returnMessage", "success");
		return result;
	}

	/**
	 * 获取Bing背景图
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getBingWallPaper")
	@ResponseBody
	public String getBingWallPaper(HttpServletRequest request, HttpServletResponse response) {
		String url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
		JSONObject ob = HttpUtils.doGet(url,null);
		JSONArray imagesArr = (JSONArray) ob.get("images");
		ob = (JSONObject) imagesArr.get(0);
		return "https://cn.bing.com/"+ob.get("url");
	}

	public static void main(String[] args) {
		JSONObject ob = new JSONObject();
		String url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
		ob = HttpUtils.doGet(url,null);
		JSONArray imagesArr = (JSONArray) ob.get("images");
		ob = (JSONObject) imagesArr.get(0);
		String im = HttpUtils.doGetString("https://cn.bing.com/"+ob.get("url"),null);
		System.out.println(im);
	}

}
